package cn.lili.controller.feign.order;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.distribution.entity.enums.DistributionStatusEnum;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.order.order.client.RankingDistributionClient;
import cn.lili.modules.order.order.entity.dos.RankingDistribution;
import cn.lili.modules.order.order.entity.dto.RankingFySetParentChildCountDTO;
import cn.lili.modules.order.order.service.IRankingDistributionService;
import com.alibaba.fastjson.JSONObject;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author: ftyy
 * @date: 2022-01-13 17:37
 * @description: 订单日志Feign
 */
@RestController
@Slf4j
public class RankingDistrbutionFeignController implements RankingDistributionClient {

    @Autowired
    private IRankingDistributionService rankingDistributionService;

    @Autowired
    private UserClient userClient;

    @Autowired
    private UserApi userApi;

    /**
     * 审核通过后，同步分销员数据
     * @param distribution 分销员数据
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(Distribution distribution) {
        log.info("#RankingDistrbutionFeignController# sync store data, 同步店主数据 == {}", JSONObject.toJSONString(distribution));
        RankingDistribution saveEntry = new RankingDistribution();
        BeanUtils.copyProperties(distribution, saveEntry);

        distribution.setDistributionStatus(DistributionStatusEnum.PASS.name());
        //已存在用户，去修改不去，新增
        RankingDistribution distributionServiceOne = rankingDistributionService.getOne(new LambdaQueryWrapper<RankingDistribution>().eq(RankingDistribution::getMemberId, saveEntry.getMemberId()));
        if (distributionServiceOne != null && StringUtils.isNotEmpty(distributionServiceOne.getId())) {
            saveEntry.setId(distributionServiceOne.getId());
        }
        //查询上级信息
        User user = userClient.getById(saveEntry.getMemberId());
        log.info("#RankingDistrbutionFeignController# sync store data,查询上级信息userClient,参数:,{},结果为,{}", saveEntry.getMemberId(), (null != user ? JSONObject.toJSONString(user) : null));
        if (null != user) {
            //这里给账号id和账号赋值
            saveEntry.setFyName(StringUtils.isNotEmpty(user.getFyName()) ? user.getFyName() : null);
            saveEntry.setAccount(StringUtils.isNotEmpty(user.getAccount()) ? user.getAccount() : null);
            //查询店长的下级人数
            String childCount = userApi.getChildCount(user.getOpenId());
            log.info("#RankingDistrbutionFeignController# sync store data,参数:user.openId:{}, userApi.getChildCount():{}", user.getOpenId(), childCount);
            saveEntry.setChildCount(StringUtils.isNotEmpty(childCount) ? Integer.parseInt(childCount) : 0);
            //根据openId查询上级
            String parentOpenId = userApi.getParent(user.getOpenId());
            log.info("sync store data上级openid:{}", parentOpenId);
          if (StringUtils.isNotEmpty(parentOpenId)) {
              //查询上级信息
              User parentUser = userClient.getByOpenId(parentOpenId, SceneEnums.MEMBER.name());
              log.info("#RankingDistrbutionFeignController# sync store data, userClient.getByOpenId() result:{}", JSONObject.toJSONString(parentUser));
              //赋值上级id,邀请人ID
              if(null != parentUser){
                  //赋值上级id
                  saveEntry.setParentId(parentUser.getId());
                  saveEntry.setParentFyName(StringUtils.isNotEmpty(parentUser.getFyName()) ? parentUser.getFyName() : null);
              }
          }
        }
        saveEntry.setLevel(1);
        saveEntry.setDirectOrderNumber(0);
        saveEntry.setGrossCommission(BigDecimal.valueOf(0));
        saveEntry.setRebateTotal(BigDecimal.valueOf(0));
        saveEntry.setAuditTime(new Date());


        return rankingDistributionService.saveOrUpdate(saveEntry);
    }

    /**
     * 飞语绑定上级,检测是否是商城店主,并对商城的店主执行下级+1操作
     * @param dto
     * @return
     */
    @Override
    public Boolean fySetParentSyncMallRankingDistribution(RankingFySetParentChildCountDTO dto) {
        log.info("RankingDistrbutionFeignController #fySetParentSyncMallRankingDistribution# 参数为,{}", JSONObject.toJSONString(dto));
        boolean flag = false;
        String parentOpenId = dto.getParentOpenId();
        Integer num = dto.getNum();
        if (StringUtils.isEmpty(parentOpenId) || null == num || num == 0) {
            return flag;
        }
        User parentUser = userClient.getByOpenId(parentOpenId, SceneEnums.MEMBER.name());
        log.info("RankingDistrbutionFeignController #fySetParentSyncMallRankingDistribution# userClient查询openId为{},Scene为MEMBER,到的结果为:{}", parentOpenId, (null != parentUser ? JSONObject.toJSONString(parentUser) : "null,取消+1操作"));
        if (null == parentUser) {

            return flag;
        }
        LambdaQueryWrapper<RankingDistribution> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RankingDistribution::getMemberId, parentUser.getId());
        queryWrapper.eq(RankingDistribution::getDeleteFlag, Boolean.FALSE);
        log.info("RankingDistrbutionFeignController #fySetParentSyncMallRankingDistribution# 查询条件memberId为:{}", parentUser.getId());
        RankingDistribution distribution = rankingDistributionService.getOne(queryWrapper);
        log.info("RankingDistrbutionFeignController #fySetParentSyncMallRankingDistribution# 查询RankingDistribution对象结果为:{}", null != distribution ? JSONObject.toJSONString(distribution) : ("不是店长,不执行+1操作"));
        if (null != distribution) {
            RankingDistribution newDomain = new RankingDistribution();
            newDomain.setId(distribution.getId());
            newDomain.setChildCount(num);
            flag = rankingDistributionService.updateRankingDistribution(newDomain) > 0;
            log.info("#fySetParentSyncMallRankingDistribution# 飞语绑定上级,检测是否是商城店主,并对商城的店主执行下级+1操作,{}", (flag ? "成功" : "失败"));
        }
        return flag;
    }

    /**
     * 清退分销商,移除排名店长
     * @param distribution
     * @return
     */
    @Override
    public Boolean removeRankingDistribution(Distribution distribution) {
        LambdaQueryWrapper<RankingDistribution> countQuery = new LambdaQueryWrapper<RankingDistribution>();
        countQuery.eq(RankingDistribution::getMemberId, distribution.getMemberId());
        countQuery.eq(RankingDistribution::getDeleteFlag, Boolean.FALSE);
        List<RankingDistribution> rankingDistribution = rankingDistributionService.list(countQuery);
        if (CollectionUtil.isNotEmpty(rankingDistribution)) {
            for (RankingDistribution rankingDistribution1 : rankingDistribution) {
                rankingDistribution1.setDistributionStatus(DistributionStatusEnum.RETREAT.name());
            }
            return rankingDistributionService.removeBatchByIds(rankingDistribution.stream().map(RankingDistribution::getId).toList());
        }
        return false;
    }

    @Override
    public Boolean updateRankingDistribution(RankingDistribution dis) {
        LambdaUpdateWrapper<RankingDistribution> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RankingDistribution::getMemberId, dis.getMemberId());
        updateWrapper.set(RankingDistribution::getParentFyName, dis.getParentFyName());
        updateWrapper.set(RankingDistribution::getParentId, dis.getParentId());
        return rankingDistributionService.update(updateWrapper);
    }

    /**
     * 清空上级ID
     * @param dis 用户信息
     * @return 是否成功
     */
    @Override
    public Boolean clearParentInfo(Distribution dis) {
        log.info("clearParentInfo -- dis == {}", JSONObject.toJSONString(dis));
        LambdaUpdateWrapper<RankingDistribution> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RankingDistribution::getMemberId, dis.getMemberId());
        updateWrapper.eq(RankingDistribution::getDistributionStatus, DistributionStatusEnum.PASS.name());
        updateWrapper.set(RankingDistribution::getParentId, null);
        updateWrapper.set(RankingDistribution::getParentFyName, null);
        boolean update = rankingDistributionService.update(updateWrapper);
        log.info("clearParentInfo == {}" , update);
        return update;
    }
}
